//
//  CartoonListViewController.swift
//  UUCartoon
//
//  Created by Galaxy on 2021/5/6.
//  Copyright © 2021 qykj. All rights reserved.
//  漫画列表页面
import UIKit
import JXSegmentedView
import ESPullToRefresh
import UICollectionViewLeftAlignedLayout
class CartoonListViewController: BaseViewController, JXSegmentedListContainerViewListDelegate {
    // 区分当前是那一列
    public var index: Int = 0
    public var websiteModel:WebsiteBaseModel = WebsiteBaseModel.init()
    public var pageNum: Int = 1
    // 记录是否有弹窗
    private var is_show: Bool = false
    // 排序时候用的时间和类型
    private var timeType: Int = 0
    private var categoryType: Int = 0
    // 区分当前是选择类型还是时间
    private var chooseType: Int = 0
    // 保存排序方式
    private var orderType: String = "/post"
    // 保存获取分类类表
    private var categoryArr: [[CategoryModel]] = [[], [], [], []]
    // 保存选中的分类信息
//    private var categoryValue: [String] = ["", "", "", ""]
    private var categoryValue = (category:"",reader:"",progress:"",area:"")
    private var listArr: [CartoonModel] = []
    private var sqlTool = SqlTool.init()
    private var leftArr = SiftCategoryModel.init().getCategoryLeftArr()
    private var rightArr = SiftCategoryModel.init().getCategoryRightArr()
    @objc func injected() {
        viewDidLoad()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        if index == 2 {
            // 创建分类筛选界面
            makeCategoryView()
            getCategoryData()
        }
        getListData()
    }
    // 筛选界面
    func makeCategoryView() {
        let chooseView = CategoryChooseView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 40))
        view.addSubview(chooseView)
        chooseView.btnClickBlock = { index in
                let button: UIButton = chooseView.viewWithTag(150 + index) as! UIButton
                let array = self.categoryArr[index]
                if !array.isEmpty {
                    if button.isSelected {
                        for view in self.view.subviews {
                            if view.tag == 200 {
                                view.removeFromSuperview()
                            }
                        }
                        let backView = UIView.init()
                        backView.tag = 200
                        self.view.addSubview(backView)
                        backView.backgroundColor = UIColor.color(hexString: "333333", alpha: 0.3)
                        backView.snp.makeConstraints { make in
                            make.left.right.bottom.equalToSuperview()
                            make.top.equalTo(50)
                        }
                        let layout = UICollectionViewLeftAlignedLayout.init()
                        let categoryCollectionView = CartoonCategoryCollectionView.init(frame: .zero, collectionViewLayout: layout)
                        backView.addSubview(categoryCollectionView)
                        categoryCollectionView.snp.makeConstraints { make in
                            make.left.right.top.equalToSuperview()
                            make.bottom.equalToSuperview().offset(-100)
                        }
                        categoryCollectionView.listArr = array
                        categoryCollectionView.cellItemSelectedBlock = { indexPath in
                            button.isSelected = false
                            button.setImage(UIImage.init(named: "category_row_close"), for: .normal)
                            button.setTitleColor(UIColor.init(named: "333333"), for: .normal)
                            backView.removeFromSuperview()
                            //                    赋值，并刷新列表
                            let categoryModel = array[indexPath.row]
                            if self.websiteModel.type == .ykmh || self.websiteModel.type == .wudi {
                                for model in array {
                                    model.isSelect = false
                                }
                            }
                            categoryModel.isSelect = true
                            if index == 0 {
                                self.categoryValue.category = categoryModel.value
                            }else if index == 1{
                                self.categoryValue.reader = categoryModel.value
                            }else if index == 2{
                                self.categoryValue.progress = categoryModel.value
                            }else if index == 3{
                                self.categoryValue.area = categoryModel.value
                            }
                            self.pageNum = 1
                            self.listArr = []
                            self.getListData()
                        }
                    } else {
                        for view in self.view.subviews {
                            if view.tag == 200 {
                                view.removeFromSuperview()
                            }
                        }
                    }
                } else {
                    self.view.makeToast("当前未获取分类信息")
                }
        }
    }
    // 保存漫画记录
    func saveCartoonList(list: [CartoonModel]) {
        for item in list {
            item.cartoon_id = sqlTool.insertCartoon(model: item)
        }
    }
    //MARK: 获取漫画列表
    func getListData() {
        beginProgress()
        DispatchQueue.global().async { [self] in
            if index == 0 {
                //MARK: 最新发布
                DataTool.init().getNewCartoonData(type: websiteModel.type, pageNum: pageNum) { resultArr in
                    DispatchQueue.main.async { [self] in
                        endProgress()
                        mainTable.es.stopPullToRefresh()
                        if !resultArr.isEmpty {
                            pageNum += 1
                            mainTable.es.stopLoadingMore()
                        }
                        saveCartoonList(list: resultArr)
                        listArr.append(array: resultArr)
                        mainTable.listArr = listArr
                    }
                }
            } else if index == 1 {
                //MARK: 漫画排行
                DataTool.init().getRankCartoonData(type: websiteModel.type, pageNum: pageNum) { resultArr in
                    DispatchQueue.main.async { [self] in
                        endProgress()
                        mainTable.es.stopPullToRefresh()
                        saveCartoonList(list: resultArr)
                        listArr = resultArr
                        mainTable.listArr = listArr
                    }
                }
            } else if index == 2 {
                //MARK: 分类筛选
                DataTool.init().getCategorySiftResultListData(type: websiteModel.type, condition: categoryValue, page: pageNum, success: { resultArr in
                    DispatchQueue.main.async { [self] in
                        endProgress()
                        mainTable.es.stopPullToRefresh()
                        if !resultArr.isEmpty {
                            pageNum += 1
                            mainTable.es.stopLoadingMore()
                        }
                        saveCartoonList(list: resultArr)
                        listArr.append(array: resultArr)
                        mainTable.listArr = listArr
                    }
                })
            } else if index == 3 {
                //MARK: 已完结
                DataTool.init().getDoneCartoonData(type: websiteModel.type, page: pageNum) { resultArr in
                    DispatchQueue.main.async { [self] in
                        endProgress()
                        mainTable.es.stopPullToRefresh()
                        if !resultArr.isEmpty {
                            pageNum += 1
                            mainTable.es.stopLoadingMore()
                        }
                        saveCartoonList(list: resultArr)
                        listArr.append(array: resultArr)
                        mainTable.listArr = listArr
                    }
                }
            }
        }
    }
    // 获取分类数据
    func getCategoryData() {
        DispatchQueue.global().async {
            DataTool.init().getCategoryData(type: self.websiteModel.type, success: { resultArr in
                self.categoryArr = resultArr
            })
        }
    }
    // 漫画列表
    lazy var mainTable: UUTableView = {
        let tableView = UUTableView.init(frame: .zero, style: .plain)
        view.addSubview(tableView)
        tableView.estimatedRowHeight = 150
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            if self.index == 1 {
                make.top.equalToSuperview().offset(10)
            } else if self.index == 2 {
                make.top.equalToSuperview().offset(40)
            } else {
                make.top.equalToSuperview()
            }
        }
        tableView.register(UINib.init(nibName: "ComicTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "cell")
        tableView.cellForRow {[weak self] (indexPath) in
            let model = self!.listArr[indexPath.row]
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ComicTableViewCell
            cell.model = model
            if model.is_rank {
                cell.rankLab.text = "\(indexPath.row+1)"
                cell.rankView.addRound(radio: 40, corners: UIRectCorner.bottomLeft)
                let colorArr = ["ff4b4b","ff8004","ffc000","dfdfdf"]
                if indexPath.row < 3{
                    cell.rankView.backgroundColor = UIColor.color(hexString: colorArr[indexPath.row])
                }else{
                    cell.rankView.backgroundColor = UIColor.color(hexString: colorArr[3])
                }
            }else{
                cell.rankViewConstraintWidth.constant = 40
            }
            return cell
        }
        tableView.cellItemDidSelected {[weak self] (indexPath) in
            let model = self!.listArr[indexPath.row]
            let VC = ChapterViewController.init()
            VC.type = self!.websiteModel.type
            VC.cartoon_id = model.cartoon_id
            VC.detailUrl = model.detailUrl
            self?.navigationController?.pushViewController(VC, animated: true)
        }
        tableView.es.addInfiniteScrolling(animator: footer) {[weak self] in
            if self!.index == 1 {
                tableView.es.stopLoadingMore()
            } else {
                self!.getListData()
            }
        }
        tableView.es.addPullToRefresh(animator: header) {[weak self] in
            self!.pageNum = 1
            self!.listArr = []
            self!.getListData()
        }
        return tableView
    }()
    func listView() -> UIView {
        view
    }
}
